package com.unstoppedable.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import net.sf.json.JSONObject;

import org.xml.sax.SAXException;

import com.unstoppedable.common.Configure;
import com.unstoppedable.common.HttpService;
import com.unstoppedable.common.Signature;
import com.unstoppedable.common.XMLParser;
import com.unstoppedable.protocol.UnifiedOrderReqData;

/**
 * Servlet implementation class PayTest
 */
public class PayTest extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PayTest() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 UnifiedOrderReqData reqData = new UnifiedOrderReqData.UnifiedOrderReqDataBuilder("wx88235ac607490e53", "1247070901",
	                "test", new Date().getTime()+"", 1, "127.0.0.1", "http://www.baidu.com", "JSAPI").setOpenid("oZ3x1jizqDWWScs8r76Ya-9gJyAY").build();
	       try {
			Map<String,Object> map=UnifiedOrder(reqData);
			Map<String,Object> paramM=new HashMap<String,Object>();
			paramM.put("appId", map.get("appid"));
			paramM.put("timeStamp", new Date().getTime()/1000+"");
			paramM.put("nonceStr",map.get("nonce_str"));
			paramM.put("package", "prepay_id="+map.get("prepay_id"));
			paramM.put("signType","MD5");
			paramM.put("paySign", Signature.getSign(paramM));
			System.out.println("========================="+paramM);
			JSONObject jsonObject = JSONObject.fromObject(paramM);
			response.setCharacterEncoding("utf-8");
			PrintWriter out=response.getWriter();
			out.print(jsonObject.toString());
			out.close();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	  public Map<String, Object> UnifiedOrder(UnifiedOrderReqData reqData) throws IOException, SAXException, ParserConfigurationException {
	        String res = HttpService.doPost(Configure.UNIFIED_ORDER_API, reqData);
	       
	        return XMLParser.getMapFromXML(res);
	    }

	  
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request,response);
	}

}
